<script setup>
import {
    reactive,
    ref,
    onMounted,
    getCurrentInstance,
    computed,
    watch,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import MainContent from "@/components/mainContent.vue";
import AI from "@/components/ai.vue";
import aiBottom from "@/components/aiButton.vue";
import { showSuccessToast } from "vant";

// 获取实例和路由
const {
    proxy: { $http },
} = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const dataVal = reactive({
    imgList: {},
    socketData: null,
    messages: [
        {
            isSent: false,
            isVoice: false,
            rawText:
                "你好，小朋友！请说出你想画的图片，比如：一只乌龟在河边奋力的追着。",
            showFrom: false,
            text: "你好，小朋友！请说出你想画的图片，比如：一只乌龟在河边奋力的追着。",
            time: new Date().toLocaleTimeString([], {
                hour: "2-digit",
                minute: "2-digit",
            }),
        },
    ],
    isStreamingResponse: false, // 新增：是否正在接收流式响应
    currentStreamingIndex: -1, // 新增：当前正在更新的消息索引
    isSubmitted:true
});

const aiComponent = ref(null);
const messageWatcher = computed(() => [...dataVal.messages]);

// 监听消息变化，确保AI组件能正确显示
watch(
    () => dataVal.messages,
    (newMessages) => {
        if (aiComponent.value && newMessages.length > 0) {
            // 确保AI组件更新显示
            setTimeout(() => {
                if (aiComponent.value.loading) {
                    const lastMessage = newMessages[newMessages.length - 1];
                    aiComponent.value.loading(
                        lastMessage.isSent,
                        false,
                        lastMessage.isVoice
                    );
                }
            }, 100);
        }
    },
    { deep: true }
);

const addMessage = (msg, one, two, isVoice) => {
    dataVal.showDialog = true;
    dataVal.messages = Array.isArray(msg) ? [...msg] : [msg];
    setTimeout(() => {
        loading(one, false, isVoice);
    }, 300);
};
const loading = async (one, two, isVoice) => {
    if (dataVal.showDialog) {
        await aiComponent.value.loading(one, two, isVoice);
    } else {
        console.error(
            "AI 组件或 loading 方法不存在",
            dataVal.showDialog,
            aiComponent.value?.loading
        );
    }
};
const answer = (item) => {
    dataVal.imgList = item
    dataVal.isSubmitted=false
    setTimeout(() => {
        loading(false, false, false);
    }, 300);
};
const submit = () => {
    $http.post('/student/commitImages', dataVal.imgList).then(res => {
        if (res.code == 200) {
            showSuccessToast('提交成功')
            dataVal.isSubmitted = true
        }
    })
}
// 结束流式响应
const endStreamingResponse = () => {
    dataVal.isStreamingResponse = false;
    dataVal.currentStreamingIndex = -1;
};

// 页面加载时获取数据
onMounted(async () => { });
</script>

<template>
    <!-- 主体内容区域 -->
    <MainContent contentWidth="95%" padding="24px">
        <template #content>
            <!-- 左右分栏容器：Flex 布局 -->
            <div class="content-layout d-flex gap-1 flex-1 height100 boderbox">
                <!-- 左侧：图片区域 -->
                <div class="content-image">
                    <div class="size-20 font-bold mt-2">AI作图</div>
                    <AI :data="messageWatcher" ref="aiComponent" />
                    <!-- 底部输入区域 -->
                    <aiBottom @add="addMessage" @onLoad="loading" :socketData="dataVal.socketData" @answer="answer"
                        @end-streaming="endStreamingResponse" />
                </div>
                <!-- 右侧：文字区域 -->
                <div class="content-text pl-4 pr-4 borderbox flex-1 height100">
                    <div class="size-20 font-bold mt-2">AI图片生成</div>
                        <div class="d-flex gap-2 images-content">
                            <img :src="item" v-for="item in dataVal.imgList.images" />
                        </div>
                        <van-button class="submit d-flex space-around align-items-center mt-1"
                            :disabled="dataVal.isSubmitted" @click="submit">提交</van-button>
                    </div>
                </div>
        </template>
    </MainContent>
</template>

<style scoped lang="scss">
.teacher-page {
    min-height: calc(100vh - 150px);
    background-color: #f5f7fa;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
// 左右分栏布局核心样式
.content-layout {
    display: flex;
    align-items: center;
    gap: 25px;
    width: 100%;
    height: 80%;

    // 响应式适配：小屏幕（≤768px）切换为上下布局
    @media (max-width: 768px) {
        flex-direction: column;
        gap: 16px;
    }
}

// 左侧文字区域样式
.content-text {
    width: 60%; // 左侧宽度占比
    border-radius: 12px;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);

    .submit {
        margin: 0 auto;
        background-color: #E95294;
        font-size: 20px;
        font-weight: bold;
        width: 160px;
        height: 60px;
        border-radius: 8px;
        color: #fff;
    }

    .images-content {
        height: calc(100% - 130px);
        flex-wrap: wrap;

        img {
            width: 31%;
            height: 170px;
            object-fit: cover;
            border-radius: 6px;
        }
    }

    // 响应式适配：小屏幕占满宽度
    @media (max-width: 768px) {
        width: 100%;
        text-align: center;
    }

    .text-content {
        color: #666;
        text-indent: 2em;
        font-family: KaiTi;
        font-weight: 400;
        font-style: Regular;
        font-size: 36px;
        line-height: 80px;
        letter-spacing: 20%;
        text-align: justify;


        .text-paragraph {
            margin: 0 0 20px 0;
            word-wrap: break-word;
            word-break: break-word;
            white-space: normal; // 允许正常换行
            animation: fadeIn 3s linear;

            &:last-child {
                margin-bottom: 0;
            }
        }
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

// 中间分隔线样式
.content-divider {
    width: 2px;
    height: 400px;
    background-color: #000000;

    // 响应式适配：小屏幕改为水平分隔线
    @media (max-width: 768px) {
        width: 100%;
        height: 1px;
        margin: 8px 0;
    }
}

// 右侧图片区域样式
.content-image {
    width: 30%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);

    // 响应式适配：小屏幕占满宽度
    @media (max-width: 768px) {
        width: 100%;
    }

    .image-item {
        width: 400px;
        height: auto;
        max-height: 640px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        object-fit: cover;
    }

    .image-desc {
        margin-top: 12px;
        color: #999;
        font-size: 12px;
        text-align: center;
    }
}

// 响应式调整
@media (max-width: 375px) {
    .main-content {
        padding: 16px;
    }

    .book-card {
        max-width: 240px;

        .book-cover {
            .cover-image {
                height: 240px;
            }
        }

        .start-teaching-btn {
            font-size: 16px;
            padding: 10px 20px;
        }
    }
}
</style>
